package com.doyens.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doyens.gmall.common.cache.GmallCache;
import com.doyens.gmall.model.product.*;
import com.doyens.gmall.product.mapper.*;
import com.doyens.gmall.product.service.ManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private BaseCatrgoryViewMapper baseCatrgoryViewMapper;

    @Override
    public List<BaseCategory1> getCategory1() {
        //完成查询所有一级分类
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        QueryWrapper<BaseCategory2> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category1_id",category1Id);
        return baseCategory2Mapper.selectList(queryWrapper);
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        QueryWrapper<BaseCategory3> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category2_id",category2Id);
        return baseCategory3Mapper.selectList(queryWrapper);
    }

    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.selectBaseAttrInfoList(category1Id,category2Id,category3Id);
    }

    @Override
    /**
     * 事务
     * 判断baseAttrInfo有没有主键
     *   没有主键走添加
     *       添加对应的值
     *   有主键走修改
     *      删除当前属性对应的所有值
     *      重新添加新的值
     */
    @Transactional //事务
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        if(baseAttrInfo.getId()==null){
            //走添加
            baseAttrInfoMapper.insert(baseAttrInfo);
        }else{
            //走修改
            baseAttrInfoMapper.updateById(baseAttrInfo);
            //删除base_attr_value表中，attr_id=值的行
            QueryWrapper<BaseAttrValue> baseAttrValueQueryWrapper = new QueryWrapper<>();
            baseAttrValueQueryWrapper.eq("attr_id",baseAttrInfo.getId());
            baseAttrValueMapper.delete(baseAttrValueQueryWrapper);
        }

        //添加属性值操作,循环添加多个平台属性值
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        for (BaseAttrValue baseAttrValue : attrValueList) {
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            baseAttrValueMapper.insert(baseAttrValue);
        }
    }

    @Override
    public IPage<SpuInfo> getSpuInfoPage(Page<SpuInfo> pageParam, SpuInfo spuInfo) {
        QueryWrapper<SpuInfo> spuInfoQueryWrapper = new QueryWrapper<>();
        spuInfoQueryWrapper.eq("category3_id",spuInfo.getCategory3Id());
        //pageParam  limit 1:10
        //spuInfoQueryWrapper where category3_id=61
        IPage<SpuInfo> page = spuInfoMapper.selectPage(pageParam, spuInfoQueryWrapper);
        return page;
    }

    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
        // 1 保存到spuinfo
        //spuInfo保存到数据库成功后，会把id设置给这个对象
        spuInfoMapper.insert(spuInfo);
        //2 保存到spu_image
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        for (SpuImage spuImage : spuImageList) {
            //手动设置图片所属的spu
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        }
        //3 保存到spu_sale_attr
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
            //手动设置属性所属的spu
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);
            //4 保存到spu_sale_attr_value
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
            for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                //手动设置所属的spu
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                //手动设置所属的销售属性名
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            }
        }

    }

    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        QueryWrapper<SpuImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id",spuId);
        return  spuImageMapper.selectList(queryWrapper);
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
       List<SpuSaleAttr> spuSaleAttrList =  spuSaleAttrMapper.getSpuSaleAttrList(spuId);
        return spuSaleAttrList;
    }

    @Override
    public BaseCategoryView getCategoryView(Long category3Id) {
        QueryWrapper<BaseCategoryView> baseCategoryViewQueryWrapper = new QueryWrapper<>();
        baseCategoryViewQueryWrapper.eq("category3_id",category3Id);
        return baseCatrgoryViewMapper.selectOne(baseCategoryViewQueryWrapper);
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {

        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId,spuId);
    }

    @Override
    @GmallCache(prefix = "category")
    public List<JSONObject> getBaseCategoryList() {
        //查询所有分类
        List<BaseCategoryView> baseCategoryViews = baseCatrgoryViewMapper.selectList(null);
        //存所有一级分类的数据
        List<JSONObject> list1 = new ArrayList<>();
        //根据一级分类id，分组汇总数据
        Map<Long, List<BaseCategoryView>> category1Map = baseCategoryViews.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        Long index=1l;
        for (Map.Entry<Long, List<BaseCategoryView>> list1Entry : category1Map.entrySet()) {
            //把每个一级分类，封装成一个JSONObject
            JSONObject jsonObject1 = new JSONObject();
            Long category1Id = list1Entry.getKey();
            List<BaseCategoryView> baseCategoryViews1 = list1Entry.getValue();

            jsonObject1.put("index",index++);
            jsonObject1.put("categoryName",baseCategoryViews1.get(0).getCategory1Name());
            jsonObject1.put("categoryId",category1Id);

            //存当前一级分类下的所有二级分类信息
            List<JSONObject> list2 = new ArrayList<>();
            //根据二级分类id，分组汇总数据
            Map<Long, List<BaseCategoryView>> category2Map = baseCategoryViews1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            //遍历map
            for (Map.Entry<Long, List<BaseCategoryView>> list2Entry : category2Map.entrySet()) {
                //创建JSONObject 存当前的二级分类信息
                JSONObject jsonObject2 = new JSONObject();
                //把每个二级分类数据，封装成一个JSONObject
                Long category2Id = list2Entry.getKey();
                List<BaseCategoryView> baseCategoryViews2 = list2Entry.getValue();


                jsonObject2.put("categoryName",baseCategoryViews2.get(0).getCategory2Name());
                jsonObject2.put("categoryId",category2Id);

                //放当前二级分类下的所有三级分类信息
                List<JSONObject> list3 = new ArrayList<>();
                for (BaseCategoryView baseCategoryView3 : baseCategoryViews2) {
                    Long category3Id = baseCategoryView3.getCategory3Id();
                    String category3Name = baseCategoryView3.getCategory3Name();
                    JSONObject jsonObject3 = new JSONObject();
                    jsonObject3.put("categoryId",category3Id);
                    jsonObject3.put("categoryName",category3Name);
                    list3.add(jsonObject3);
                }

                jsonObject2.put("categoryChild",list3);
                list2.add(jsonObject2);
            }
            jsonObject1.put("categoryChild",list2);
            list1.add(jsonObject1);
        }



       /* //根据一级分类的id，分组
        Map<Long,List<BaseCategoryView>> category1Map = new HashMap<>();
        //遍历所有分类信息
        for (BaseCategoryView baseCategoryView : baseCategoryViews) {
            //取每条数据的一级分类id
            Long category1Id = baseCategoryView.getCategory1Id();
            //从map中取一级分类id对应的list
            List<BaseCategoryView> baseCategoryViews1 = category1Map.get(category1Id);
            //如果第一次循环category1id为1的，map没有对应的list
            if(baseCategoryViews1==null){
                //手动创建一个list
                baseCategoryViews1 = new ArrayList<>();
                //把当前的分类信息，放入list
                baseCategoryViews1.add(baseCategoryView);
                //再把一级分类id 1 和对应的list放入map中
                category1Map.put(category1Id,baseCategoryViews1);
            }else{
                //把1的list取出来
                //把第二条属于1的数据，放人list中
                baseCategoryViews1.add(baseCategoryView);
                //再把id 1和对应的list重新放入map中
                category1Map.put(category1Id,baseCategoryViews1);
            }
        }*/
        return list1;
    }

    @Override
    public List<BaseAttrInfo> getAttrList(Long skuId) {
        List<BaseAttrInfo> attrList = baseAttrInfoMapper.getAttrList(skuId);
        return attrList;
    }
}
